package com.lvchen.ui.fourfunction.photograph;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.cv4j.core.binary.Threshold;
import com.cv4j.core.datamodel.ByteProcessor;
import com.cv4j.core.datamodel.CV4JImage;
import com.googlecode.tesseract.android.TessBaseAPI;
import com.lvchen.R;
import com.lvchen.common.base.BaseActivity;
import com.lvchen.common.utils.ImageFilter;
import com.lvchen.common.utils.UIHelper;
import com.lvchen.network.ConstantKey;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.siberiadante.titlelayoutlib.TitleBarLayout;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 拍照测试
 */
public class TakePhotoActivity extends BaseActivity implements View.OnClickListener {

    private String path = "";
    private int flag = 0;

    private TitleBarLayout tb_title;
    private RoundedImageView img_photo_head, img_photo_headback;
    private TextView tv_photo_ocr;

    private String ocr = "";

    /* mDataPath 是字库在手机上的存储位置 */
    private String mDataPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tessdata/";



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_takephoto);
        ensureUi();



    }

    private void ensureUi() {

        tb_title = (TitleBarLayout) findViewById(R.id.tb_title);
        tb_title.setIsHaveLine(false);

        img_photo_head = (RoundedImageView) findViewById(R.id.img_photo_head);
        img_photo_headback = (RoundedImageView) findViewById(R.id.img_photo_headback);
        tv_photo_ocr = (TextView) findViewById(R.id.tv_photo_ocr);

        img_photo_head.setOnClickListener(this);
        img_photo_headback.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_photo_head://人像
                flag = 1;
                Intent intent1 = new Intent(TakePhotoActivity.this, MyCameraActivity.class);
                intent1.putExtra("flag", flag);
                startActivityForResult(intent1, ConstantKey.MYCAMERA);
                break;
            case R.id.img_photo_headback://国徽
                flag = 2;
                Intent intent2 = new Intent(TakePhotoActivity.this, MyCameraActivity.class);
                intent2.putExtra("flag", flag);
                startActivityForResult(intent2, ConstantKey.MYCAMERA);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (ConstantKey.MYCAMERA == requestCode) {
            if (data != null) {
                path = data.getStringExtra("fileaddress");
                if (!TextUtils.isEmpty(path)) {
                    setimg();
                }
            }
        }

    }

    private void setimg() {

        if (1 == flag) {
            ImageLoader.getInstance().displayImage("file:///" + path, img_photo_head);

            startocr();

        } else if (2 == flag) {
            ImageLoader.getInstance().displayImage("file:///" + path, img_photo_headback);

            startocr();

        }

    }

    private void  startocr(){
        OcrTask ocrTask = new OcrTask();
        ocrTask.execute();
    }

    private void copyFiles() {
        String[] datafilepaths = new String[]{mDataPath + "/chi_sim.traineddata", mDataPath + "/eng.traineddata"}; // 拷两个字库过去
        for (String datafilepath : datafilepaths) {
            copyFile(datafilepath);
        }
    }

    private void copyFile(String datafilepath) {
        try {
            String filepath = datafilepath;
            String[] filesegment = filepath.split(File.separator);
            String filename = filesegment[(filesegment.length - 1)]; // 获取字库文件名
            AssetManager assetManager = getAssets();
            InputStream instream = assetManager.open(filename); // 打开字库文件
            OutputStream outstream = new FileOutputStream(filepath);

            byte[] buffer = new byte[1024];
            int read;
            while ((read = instream.read(buffer)) != -1) {
                outstream.write(buffer, 0, read);
            }
            outstream.flush();
            outstream.close();
            instream.close();
            File file = new File(filepath);
            if (!file.exists()) {
                throw new FileNotFoundException();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class OcrTask extends AsyncTask<String, Integer, String> {

        // 方法1：onPreExecute（）
        // 作用：执行 线程任务前的操作
        @Override
        protected void onPreExecute() {
            UIHelper.ShowLoadingView("识别中");
            // 执行前显示提示
        }


        // 方法2：doInBackground（）
        // 作用：接收输入参数、执行任务中的耗时操作、返回 线程任务执行的结果
        // 此处通过计算从而模拟“加载进度”的情况
        @Override
        protected String doInBackground(String... params) {

            File parentfile = new File(mDataPath);
            if (!parentfile.exists()){ // 确保路径存在
                parentfile.mkdir();
            }
            copyFiles(); // 复制字库到手机
            String lang = "chi_sim+eng"; // 使用简体中文 + 英文检测
            TessBaseAPI mTess = new TessBaseAPI();

            mTess.init(Environment.getExternalStorageDirectory().getAbsolutePath(), lang); // 初始化，第一个参数为 mDataPath 的父目录

            //设置白名单
//            mTess.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
            //设置黑名单
            mTess.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST, "!@#$%^&*()_+=-[]}{;:'\"\\|~`,./<>?");
            //设置识别模式
            mTess.setPageSegMode(TessBaseAPI.PageSegMode.PSM_AUTO_OSD);

            Bitmap bitmap = UIHelper.getSmallBitmap(path); // 获取测试图片

//            CV4JImage cv4JImage = new CV4JImage(bitmap);
//            Threshold threshold = new Threshold();
//            threshold.adaptiveThresh((ByteProcessor)(cv4JImage.convert2Gray().getProcessor()), Threshold.ADAPTIVE_C_MEANS_THRESH, 30, 50, Threshold.METHOD_THRESH_BINARY);
//            Bitmap newBitmap = cv4JImage.getProcessor().getImage().toBitmap(Bitmap.Config.ARGB_8888);
//            mTess.setImage(newBitmap);

//            bitmap =  ImageFilter.gray2Binary(bitmap);// 图片二值化
//            bitmap =  ImageFilter.grayScaleImage(bitmap);// 图片灰度化

            mTess.setImage(bitmap);
            ocr = mTess.getUTF8Text(); // 拿到字符串结果

//            cv4JImage.recycle();
            //            newBitmap.recycle();
            bitmap.recycle();

            mTess.clear();
            mTess.end();

            return null;
        }

        // 方法3：onProgressUpdate（）
        // 作用：在主线程 显示线程任务执行的进度
        @Override
        protected void onProgressUpdate(Integer... progresses) {



        }

        // 方法4：onPostExecute（）
        // 作用：接收线程任务执行结果、将执行结果显示到UI组件
        @Override
        protected void onPostExecute(String result) {
            // 执行完毕后，则更新UI
            tv_photo_ocr.setText(getResources().getString(R.string.ocr)+ocr);
            tv_photo_ocr.setText(ocr+"");
            UIHelper.CloseLoadingView();
        }

        // 方法5：onCancelled()
        // 作用：将异步任务设置为：取消状态
        @Override
        protected void onCancelled() {



        }
    }


    public static void goToThisActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, TakePhotoActivity.class);
        context.startActivity(intent);
    }

}
